#include "data_flood.h"
#include "libpq-fe.h"

extern THR_LOCAL PGconn* g_conn;

void check_conn(PGconn** conn)
{
    if(*conn)
        return;
    if(g_conn)
        *conn = g_conn;
    else    
        df_error("No db conn now!!");
}

void executeCommand(const char* sql)
{
    PGconn* conn = NULL;
    PGresult* res = NULL;

    check_conn(&conn);
    res = PQexec(conn, sql);
    if (PQresultStatus(res) != PGRES_COMMAND_OK) {
        char* temp_str = NULL;
        PQclear(res);
        temp_str = strdup(PQerrorMessage(conn));
        doDisconnect();
        df_error(temp_str);
    }
    PQclear(res);
}

PGresult* executeQuery(const char* sql, bool permit_error)
{
    PGconn* conn = NULL;
    PGresult* res = NULL;

    check_conn(&conn);
    res = PQexec(conn, sql);
    if (PQresultStatus(res) != PGRES_TUPLES_OK && !permit_error) {
        char* temp_str = NULL;
        PQclear(res);
        temp_str = strdup(PQerrorMessage(conn));
        doDisconnect();
        df_error(temp_str);
    }
    return res;
}

void doPrepare(char *sql, int paranum, char* stmt_name)
{
    PGresult*   res = NULL;
    PGconn* conn = NULL;

    check_conn(&conn);
    res = PQprepare(conn, stmt_name, sql, paranum, NULL);
    if (PQresultStatus(res) != PGRES_COMMAND_OK) {
        char* temp_str = NULL;
        PQclear(res);
        temp_str = PQerrorMessage(conn);
        doDisconnect();
        df_error(temp_str);
    }
    PQclear(res);
}

void executePrepared(char* stmt_name, char** paramValues, int argnum)
{
    PGresult    *res = NULL;
    PGconn      *conn = NULL;

    check_conn(&conn);
    res = PQexecPrepared(conn, stmt_name, argnum, (const char* const*)paramValues, NULL, NULL, 1);
    if (PQresultStatus(res) != PGRES_COMMAND_OK) {
        char* temp_str = NULL;
        PQclear(res);
        temp_str = PQerrorMessage(conn);
        doDisconnect();
        df_error(temp_str);
    }
    PQclear(res);
}